import { DataSet } from 'choerodon-ui/pro';
import { CONSTANTS } from '@choerodon/master';
import { FieldProps, FieldType, Record } from '@/interface';
import { deployAppCenterApiConfig, deployAppCenterApi } from '@/api/DeployAppCenter';
import { deployWayData } from './constants';

const {
  LCLETTER_NUMREGEX,
} = CONSTANTS;

const appNameDataSet = new DataSet({
  autoQuery: false,
  paging: true,
  transport: {
    read: (params) => {
      const data = params?.data?.envId;
      return deployAppCenterApiConfig.getDeployCenterAppList({
        rdupm_type: 'deployment',
        ...params?.params || {},
        env_id: data,
      });
    },
  },
});

const mapping = (): {
  [key: string]: FieldProps
} => ({
  appName: {
    name: 'appName',
    type: 'string' as FieldType,
    label: '应用名称',
    textField: 'name',
    valueField: 'id',
    options: appNameDataSet,
  },
  appCode: {
    name: 'appCode',
    type: 'string' as FieldType,
    label: '应用编码',
  },
});

const deployGroupDataSet = (ADDCDTaskDataSet: DataSet, level: any) => ({
  autoCreate: true,
  fields: Object.keys(mapping()).map((i) => {
    const item = mapping()[i];
    switch (i) {
      case 'appName': {
        item.disabled = level !== 'project' || window.location.href.includes('project-pipeline-template');
        item.required = level === 'project' && !window.location.href.includes('project-pipeline-template');
        item.validator = async (value: string) => {
          if (value) {
            if (ADDCDTaskDataSet.current?.get('deployType') === deployWayData[0].value) {
              try {
                const res = await deployAppCenterApi.checkAppName(value, undefined, undefined, ADDCDTaskDataSet.current?.get('envId'));
                if (res) {
                  return true;
                }
                return '名称重复';
              } catch (e) {
                return '校验出错';
              }
            } else {
              return true;
            }
          }
          return true;
        };
        break;
      }
      case 'appCode': {
        item.required = level === 'project' && !window.location.href.includes('project-pipeline-template');
        item.dynamicProps = {
          disabled: ({ record }: { record: Record }) => {
            let flag = false;
            if (ADDCDTaskDataSet.current?.get('deployType') === deployWayData[1].value) {
              flag = true;
            }
            if (!ADDCDTaskDataSet.current?.get('envId')) {
              flag = true;
            }
            if (level !== 'project') {
              flag = true;
            }
            return flag;
          },
        };
        item.validator = async (value: string) => {
          if (value) {
            let flag: any = true;
            if (!LCLETTER_NUMREGEX.regex.test(value)) {
              flag = LCLETTER_NUMREGEX.text;
            }
            if (ADDCDTaskDataSet.current?.get('deployType') === deployWayData[0].value) {
              try {
                const res = await deployAppCenterApi.checkAppCode(value, undefined, undefined, ADDCDTaskDataSet.current.get('envId'));
                if (!res) {
                  flag = '编码重复';
                }
              } catch (e) {
                flag = '校验出错';
              }
            }
            return flag;
          }
          return true;
        };
        break;
      }
      default: {
        break;
      }
    }
    return item;
  }),
  events: {
    update: ({ record, name, value }: {
        record: Record,
        name: string,
        value: string,
      }) => {
      switch (name) {
        case mapping().appName.name: {
          if (ADDCDTaskDataSet.current?.get('deployType') === deployWayData[1].value) {
            const item = appNameDataSet.records.find((itemRecord: Record) => itemRecord?.get('id') === value);
            if (item) {
              record?.set(mapping().appCode.name as string, item.get('code'));
            }
          }
          break;
        }
        default: {
          break;
        }
      }
    },
  },
});

export { mapping, appNameDataSet };
export default deployGroupDataSet;
